package {
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.utils.ByteArray;

	public class TcpSender extends Sprite
	{
		private static var _data:ByteArray = null;
		private static var myclient:MyClient = null;

		public function TcpSender(_host:String = null, _port:uint = 0) {
			host = _host;
			port = _port;
			_main = this;

			//super();
			//start_connect();
		}

		public static function start_connect(_host:String = null,_port:uint = 0):void
		{
			if(_host != null)
				host = _host;
			if(_port != 0)
				port = _port;

			if(_host != host || _port != port)
			{
				myclient.close();
				myclient = null;
			}
			if(myclient == null)
			{
				myclient = new MyClient(host,port);
			}
		}

		public static function send_data(bytes:ByteArray=null):void
		{
			if(bytes)
			{
				bytes.position = 0;
				var s:String = "";
				while(bytes.position < bytes.length)
				{
					var i:int = bytes.readByte() & 0xff;
					var _s:String = i.toString(16);
					while(_s.length<2)_s = "0"+_s;
					s += _s;
				}
				//showTxt(s + " 发送字节：" + bytes.length);
			}
			//return;
			if(myclient == null)
			{
				myclient = new MyClient(host,port);
			}
			myclient.send_data(bytes);
		}

		private static var _txt:TextField = null;
		public static function get stateTxt():TextField
		{
			//maketxt(xx:int, yy:int,str:String, ww:int, hh:int, size:int,autoSize:String="left",color:uint=0xffffff):TextField
			if(_txt == null)
				_txt = ViewSet.maketxt(0,1080-50,"",1920,50,22,"left",0xff0000) as TextField;
			return _txt;
		}
		public static function showTxt(s:String=null):void
		{
			if(s as String)
				stateTxt.text = s;
			else
				stateTxt.text = "";
			if(stateTxt.stage)
				stateTxt.stage.addChild(stateTxt);
		}


		private static var _main:TcpSender = null;
		private static function get main():TcpSender
		{
			if(_main == null)
				_main = new TcpSender(host,port);
			return _main;
		}
		private static var host:String = null;
		public static function set ip(s:String):void {
			host = s;
		}
		public static function set portNum(i:uint):void {
			port = i;
		}
		private static var port:uint = 0;
	}
}
import flash.errors.*;
import flash.events.*;
import flash.net.Socket;
import flash.utils.*;
class MyClient extends Socket{
	private var bytes:ByteArray = null;
	private var host:String= null;
	private var port:uint = 0;


	public function MyClient(_host:String = null, _port:uint = 0) {
		host = _host;
		port = _port;
		logs.adds("["+_host +":" + port+"]");
		super();
		configureListeners();
		start_connect();
	}

	private function start_connect():void
	{
		if (host && port)  {
			TcpSender.showTxt("连接"+host+":"+port+"中。。。");
			super.connect(host, port);
		}else if(connected){
			connectHandler(null);
		}else{
			TcpSender.showTxt("请确认配置正确，并重启程序!");
		}
	}

	private function configureListeners():void {
		addEventListener(Event.CLOSE, closeHandler);
		addEventListener(Event.CONNECT, connectHandler);
		addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
	}
	public function send_data(_data:ByteArray = null):void {
		bytes = _data;
		if(bytes)
		{
			bytes.position = 0;
			if(connected)
			{
				sends(bytes);
				bytes = null;
			}else{
				start_connect();
			}
		}
	}

	public function sends(_data:ByteArray = null):void {
		logs.adds("sendRequest");
		try {
			//writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)/
			_data.position = 0;
			writeBytes(_data);
		}
		catch(e:IOError) {
			logs.adds(e);
		}
		flush();
	}

	private function readResponse():void {
		try{
			var str:String = readUTFBytes(bytesAvailable);
			logs.adds(str);
		}catch(e:Error){
			logs.adds(e);
		}
		//close();
	}

	private function closeHandler(event:Event):void {
		logs.adds("closeHandler: " + event);
		TcpSender.showTxt("连接关闭，重新连接。。。");
		start_connect();
	}

	private function connectHandler(event:Event):void {
		logs.adds("connectHandler: " + event);
		//logs.adds("["+_host +":" + port+"]==>{" + _data +"}");
		TcpSender.showTxt("已连接"+host+":"+port+"");
		resetHideTime();

		if(bytes)
			sends(bytes);
	}

	private function ioErrorHandler(event:IOErrorEvent):void {
		logs.adds("ioErrorHandler: " + event);
		TcpSender.showTxt("连接出错");

		clearTimeout(timeoutId);
		timeoutId = setTimeout(start_connect,3000);
	}

	private function securityErrorHandler(event:SecurityErrorEvent):void {
		logs.adds("securityErrorHandler: " + event);
		TcpSender.showTxt("没有权限访问网络");
	}

	private function socketDataHandler(event:ProgressEvent):void {
		logs.adds("socketDataHandler: " + event);
		TcpSender.showTxt("已发送");
		readResponse();

		clearTimeout(timeoutId);
		timeoutId = setTimeout(hideTxt,1000);
	}

	private function resetHideTime():void
	{
		clearTimeout(timeoutId);
		timeoutId = setTimeout(hideTxt,3000);
	}

	private var timeoutId:uint;
	private function hideTxt():void
	{
		clearTimeout(timeoutId);
		TcpSender.showTxt("");
	}
}

